package com.xinqi.modules.prepare.paper.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.dto.QuestionBaseDTO;
import com.xinqi.common.base.dto.utils.QuestionStats;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.common.security.utils.UserHelp;
import com.xinqi.modules.prepare.common.dto.data.PrepareExamPaperData;
import com.xinqi.modules.prepare.common.service.PrepareAuthService;
import com.xinqi.modules.prepare.common.utils.QuestionUtils;
import com.xinqi.modules.prepare.folder.manager.PrepareFileFolderManager;
import com.xinqi.modules.prepare.paper.convert.PrepareExamPaperConvert;
import com.xinqi.modules.prepare.paper.domain.PrepareExamPaperEntity;
import com.xinqi.modules.prepare.paper.dto.req.PrepareExamPaperCreateDTO;
import com.xinqi.modules.prepare.paper.dto.req.PrepareExamPaperDeleteDTO;
import com.xinqi.modules.prepare.paper.dto.req.PrepareExamPaperQueryDTO;
import com.xinqi.modules.prepare.paper.dto.req.PrepareExamPaperRandomDTO;
import com.xinqi.modules.prepare.paper.dto.req.PrepareExamPaperUpdateDTO;
import com.xinqi.modules.prepare.paper.dto.rsp.PrepareExamPaperResultDTO;
import com.xinqi.modules.prepare.paper.manager.PrepareExamPaperManager;
import com.xinqi.modules.prepare.paper.service.PrepareExamPaperService;
import com.xinqi.modules.prepare.prepare.enums.PrepareMemberPermissionEnum;
import com.xinqi.modules.prepare.prepare.enums.PrepareOperateTypeEnum;
import com.xinqi.modules.prepare.prepare.enums.PrepareSubOperateTypeEnum;
import com.xinqi.modules.prepare.prepare.manager.PrepareOperateLogManager;
import com.xinqi.modules.prepare.question.manager.PrepareQuestionBankManager;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 备课区测评卷服务层实现
 *
 * @author: system
 * @date: 2023/03/19
 */
@Validated
@Service("prepareExamPaperService")
@RequiredArgsConstructor
public class PrepareExamPaperServiceImpl implements PrepareExamPaperService {
    private final PrepareExamPaperConvert prepareExamPaperConvert;
    private final PrepareExamPaperManager prepareExamPaperManager;
    private final PrepareQuestionBankManager prepareQuestionBankManager;
    private final PrepareAuthService prepareAuthService;
    private final PrepareFileFolderManager prepareFileFolderManager;
    private final PrepareOperateLogManager prepareOperateLogManager;

    /**
     * 分页查询 备课区测评卷数据
     */
    @Override
    @DS("slaver")
    public PageInfo<PrepareExamPaperResultDTO> page(Param pageable, PrepareExamPaperQueryDTO query) {
        IPage<PrepareExamPaperEntity> page = prepareExamPaperManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, prepareExamPaperConvert::convert);
    }

    /**
     * 查询 备课区测评卷数据
     */
    @Override
    public List<PrepareExamPaperResultDTO> find(PrepareExamPaperQueryDTO query) {
        return prepareExamPaperManager.list(wrapper(query)).stream()
            .map(prepareExamPaperConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<PrepareExamPaperEntity> wrapper(PrepareExamPaperQueryDTO query) {
        LambdaQueryWrapper<PrepareExamPaperEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(PrepareExamPaperEntity::getId, v));
        return wrapper;
    }

    /**
     * 根据id查询 备课区测评卷数据
     */
    @Override
    public PrepareExamPaperResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(prepareExamPaperManager.findById(id)).map(prepareExamPaperConvert::convert).orElse(null);
    }

    @Override
    public PrepareExamPaperData find(Long id) {
        return prepareExamPaperConvert.convert(findById(id));
    }

    /**
     * 新增 备课区测评卷数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid PrepareExamPaperCreateDTO dto) {
        prepareAuthService.check(dto.getPrepareId(), PrepareMemberPermissionEnum.新建);
        PrepareExamPaperEntity entity = prepareExamPaperConvert.create(dto);
        entity.setUserId(UserHelp.userId());
        // 处理题目汇总信息
        QuestionStats status = QuestionUtils.status(dto.getQuestionContent());
        entity.setQuestionTotal(status.getQuestionTotal());
        entity.setQuestionTypeTotal(status.getQuestionTypeTotal());
        entity.setTotalScore(status.getTotalScore());
        prepareExamPaperManager.save(entity);
        // 创建备课区文件
        prepareFileFolderManager.insertFile(entity, entity.getPrepareId(), dto.getFolderId(), dto.getIsAutoGenerateName());
        prepareOperateLogManager.addFileOperateLog(entity, PrepareOperateTypeEnum.FILE_EDIT, PrepareSubOperateTypeEnum.ADD);
        return entity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid PrepareExamPaperData data) {
        PrepareExamPaperCreateDTO dto = prepareExamPaperConvert.create(data);
        return insert(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long random(@Valid PrepareExamPaperRandomDTO dto) {
        prepareAuthService.check(dto.getPrepareId(), PrepareMemberPermissionEnum.新建);
        List<QuestionBaseDTO> questionList =  prepareQuestionBankManager.findByRandom(dto.getPrepareId(), dto.getQuestionTypeNumList());
        PrepareExamPaperCreateDTO createDTO = prepareExamPaperConvert.convert(dto);
        createDTO.setQuestionContent(questionList);
        return insert(createDTO);
    }

    /**
     * 根据id修改 备课区测评卷数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid PrepareExamPaperUpdateDTO dto) {
        PrepareExamPaperEntity old = Optional.ofNullable(prepareExamPaperManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        prepareAuthService.check(old.getPrepareId(), PrepareMemberPermissionEnum.编辑);
        PrepareExamPaperEntity entity = prepareExamPaperConvert.update(dto);
        // 处理题目汇总信息
        QuestionStats status = QuestionUtils.status(dto.getQuestionContent());
        entity.setQuestionTotal(status.getQuestionTotal());
        entity.setQuestionTypeTotal(status.getQuestionTypeTotal());
        entity.setTotalScore(status.getTotalScore());
        boolean b = prepareExamPaperManager.updateById(entity);
        if (b) {
            // 更新备课区文件
            PrepareExamPaperEntity newEntity = prepareExamPaperManager.getById(dto.getId());
            prepareFileFolderManager.updateFile(newEntity, newEntity.getPrepareId());
            prepareOperateLogManager.addFileOperateLog(newEntity, PrepareOperateTypeEnum.FILE_EDIT, PrepareSubOperateTypeEnum.EDIT);
        }
        return b;
    }

    /**
     * 根据id删除 备课区测评卷数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        PrepareExamPaperEntity entity = Optional.ofNullable(prepareExamPaperManager.getById(id))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        prepareAuthService.check(entity.getPrepareId(), PrepareMemberPermissionEnum.删除);
        boolean b = prepareExamPaperManager.deleteById(entity);
        if (b) {
            // 删除备课区文件
            prepareFileFolderManager.deleteFile(entity, entity.getPrepareId());
        }
        return b;
    }

    /**
     * 根据id删除 备课区测评卷数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(PrepareExamPaperDeleteDTO dto) {
        return deleteById(dto.getId());
    }

}
